package com.zhe.zheblogmaster.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zhe.zheblogmaster.config.BlogConstants;
import com.zhe.zheblogmaster.entity.BlogCategory;
import com.zhe.zheblogmaster.mapper.BlogCategoryMapper;
import com.zhe.zheblogmaster.mapper.BlogMapper;
import com.zhe.zheblogmaster.service.BlogCategoryService;
import com.zhe.zheblogmaster.util.ZheBlogUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author WHAOU
 */
@Service
public class BlogCategoryServiceImpl implements BlogCategoryService {
    @Autowired
    private BlogCategoryMapper categoryMapper;
    @Autowired
    private BlogMapper blogMapper;

    @Override
    public BlogCategory getCategoryById(Integer categoryId) {
        return categoryMapper.selectById(categoryId);
    }

    @Override
    public List<BlogCategory> getAll() {
        return categoryMapper.selectAllCategories();
    }

    @Override
    public Integer getTotalCategories() {
        return categoryMapper.selectCount();
    }

    @Override
    public PageInfo<BlogCategory> getCategoryPage(Integer pageNum) {
        PageHelper.startPage(pageNum, BlogConstants.DEFAULT_PAGE_SIZE);
        List<BlogCategory> categories = categoryMapper.selectAllCategories();
        return new PageInfo<>(categories);
    }

    @Override
    public Boolean addCategory(String name, String icon) {
        BlogCategory category = categoryMapper.selectByName(name);
        if (category != null) {
            return false;
        }
        category = new BlogCategory();
        category.setCategoryName(name);
        category.setCategoryIcon(icon);
        category.setCreateTime(ZheBlogUtils.getNow());
        return categoryMapper.insertSelective(category) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateCategory(Integer id, String name, String icon) {
        BlogCategory category = categoryMapper.selectById(id);
        if (category == null) {
            return false;
        }
        category.setCategoryName(name);
        category.setCategoryIcon(icon);
        blogMapper.updateBlogCategory(name, id, new Integer[]{id});
        return categoryMapper.updateByIdSelective(category) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteBatch(Integer[] ids) {
        if (ids == null || ids.length < 1) {
            return 0;
        }
        blogMapper.updateBlogCategory("默认分类", 0, ids);
        return categoryMapper.deleteBatch(ids);
    }
}
